package com.norrielm.GooglePlusPosts.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import com.norrielm.GooglePlusPosts.models.Receiver;

/**
 * Broadcasts profile updates from the server to the client.
 * 
 * @author Lauren Norrie (norrielm)
 */
public class ProfileReceiver {
	
    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;

    public ProfileReceiver(Context context, final Receiver<String> updateReceived) {   	
        // We use this to send broadcasts within our local process.
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(context);

        // We are going to watch for interesting local broadcasts.
        IntentFilter filter = new IntentFilter();
        filter.addAction(ServerReceiver.ACTION_STARTED);
        filter.addAction(ServerReceiver.ACTION_UPDATE);
        filter.addAction(ServerReceiver.ACTION_STOPPED);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(ServerReceiver.ACTION_STARTED)) {
                	//
                } else if (intent.getAction().equals(ServerReceiver.ACTION_UPDATE)) {
                	updateReceived.accept(intent.getStringExtra("value"));
                } else if (intent.getAction().equals(ServerReceiver.ACTION_STOPPED)) {
                	//
                }
            }
        };
        mLocalBroadcastManager.registerReceiver(mReceiver, filter);
    }

    public void destroy() {
        mLocalBroadcastManager.unregisterReceiver(mReceiver);
    }
}